var express = require("express");
var router = express.Router();

const { userModule } = require("../module/module");

const jwt = require("jsonwebtoken");
const multer = require("multer");
const storage = multer.memoryStorage(); // 使用内存存储上传的文件
const upload = multer({ storage: storage });

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

// 注册账号
router.post("/api/register", async (req, res) => {
  const { username, password } = req.body;
  const user = new userModule({ username, password });
  try {
    await user.save();
    res.status(200).json({ message: "注册成功" });
  } catch (error) {}
});
// 登录验证
router.post("/api/login", async (req, res) => {
  const {} = req.body;
  try {
    const token = jwt.sign({ username: "admin" }, "admin", { expiresIn: "1h" });
  } catch {
    console.log(error);
    res.status(500).json({ message: "服务器错误" });
  }
});

// 获取数据列表
router.get("/api/list", async (req, res) => {
  let data = await xxxxx.find();
  if (data.length > 0) {
    res.send(data);
  } else {
    res.send("获取失败");
  }
});

// 上传图片（未测试）
router.post("/upload", upload.single("image"), (req, res) => {
  const imgBuffer = req.file.buffer; // 获取上传图片的二进制数据
  // 将二进制数据保存到数据库中
  const newNFT = new NFT({
    nftId: 1,
    img: imgBuffer,
    name: "Some Name",
  });
  newNFT.save((err) => {
    if (err) {
      console.error(err);
      res.status(500).send("Failed to save image to database.");
    } else {
      res.status(200).send("Image uploaded successfully.");
    }
  });
});

module.exports = router;
